/*
	Copyright (c) 2010 <copyright holders>
	This source code is licensed under The MIT License,
	see the file LICENSE for details.
	*/

#include "GameGUI.hpp"

#include <QuickGUI.h>

using namespace QuickGUI;

namespace spelprog2 {
namespace gui {

GameGUI::GameGUI(Ogre::SceneManager & sceneMan, Ogre::Viewport & viewport) : WidgetRegistry(),
    guiMan_(),
    viewport_(viewport)
{
    /*  create a set of code points including English (most of Basic Latin),
        Latin-1 Supplement, Latin Extended-A and Latin Extended-B */
    std::set<Ogre::UTFString::code_point> codePoints;
    codePoints.insert(9);
    for (Ogre::UTFString::code_point i = 32; i <= 0x24f; ++i) {
        codePoints.insert(i);
    }

    //initialize GUI manager
    GUIManagerDesc managerDesc;
    managerDesc.sceneManager = &sceneMan;
    managerDesc.viewport = &viewport;
    managerDesc.queueID = Ogre::RENDER_QUEUE_OVERLAY;
    managerDesc.supportedCodePoints = codePoints;
    guiMan_ = Root::getSingleton().createGUIManager(managerDesc);
}

GameGUI::~GameGUI()
{
    Root::getSingleton().destroyGUIManager(guiMan_);
}

QuickGUI::Sheet * GameGUI::createSheet(const FloatRect & rect, AxisAlignment horizontal, AxisAlignment vertical,
        const QuickGUI::Size * maxSize) const
{
    SheetDesc & desc = *DescManager::getSingleton().getDefaultSheetDesc();
    desc.resetToDefault();

    QuickGUI::Rect viewRect;
    viewRect.size.width = float(viewport_.getActualWidth());
    viewRect.size.height = float(viewport_.getActualHeight());
    desc.widget_dimensions = layoutRect(rect, viewRect);

    if (maxSize) {
        desc.widget_dimensions.size.width = std::min(maxSize->width, desc.widget_dimensions.size.width);
        desc.widget_dimensions.size.height = std::min(maxSize->height, desc.widget_dimensions.size.height);
    }

    if (horizontal == AA_CENTER) {
        desc.widget_dimensions.position.x = (viewRect.size.width - desc.widget_dimensions.size.width) / 2;
    }
    else if (horizontal == AA_MAX) {
        desc.widget_dimensions.position.x = viewRect.size.width - desc.widget_dimensions.size.width;
    }

    if (vertical == AA_CENTER) {
        desc.widget_dimensions.position.y = (viewRect.size.height - desc.widget_dimensions.size.height) / 2;
    }
    else if (vertical == AA_MAX) {
        desc.widget_dimensions.position.y = viewRect.size.height - desc.widget_dimensions.size.height;
    }

    return SheetManager::getSingleton().createSheet(&desc);
}

QuickGUI::Rect GameGUI::layoutRect(const FloatRect & src, const QuickGUI::Rect & env)
{
    return QuickGUI::Rect(
        env.position.x + src.l * env.size.width,
        env.position.y + src.t * env.size.height,
        (src.r - src.l) * env.size.width,
        (src.b - src.t) * env.size.height
    );
}


}; //namespace gui

}; //namespace spelprog2